package com.taptech.doufu.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.view.View
import android.widget.RelativeLayout
import com.taptech.doufu.R
import android.graphics.Canvas
import android.os.Bundle
import android.os.Environment
import android.widget.Toast
import com.taptech.doufu.bean.ShareBeansInfo
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.model.novel.bean.NovelDetailBean
import com.taptech.doufu.net.retrofit.api.RxJavaHelper
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity
import com.taptech.doufu.ui.view.WaitDialog
import com.taptech.doufu.util.*
import kotlinx.android.synthetic.main.activity_novel_poster.*
import kotlinx.android.synthetic.main.activity_user_poster.ivBigPic
import kotlinx.android.synthetic.main.activity_user_poster.ivCover
import kotlinx.android.synthetic.main.activity_user_poster.ivQRCode
import kotlinx.android.synthetic.main.activity_user_poster.layBack
import kotlinx.android.synthetic.main.activity_user_poster.layContent
import kotlinx.android.synthetic.main.activity_user_poster.layDownload
import kotlinx.android.synthetic.main.activity_user_poster.layQQ
import kotlinx.android.synthetic.main.activity_user_poster.layWeibo
import kotlinx.android.synthetic.main.activity_user_poster.layWeixin
import kotlinx.android.synthetic.main.activity_user_poster.tvDesc
import kotlinx.android.synthetic.main.activity_user_poster.tvTag1
import kotlinx.android.synthetic.main.activity_user_poster.tvTag2
import kotlinx.android.synthetic.main.activity_user_poster.tvTip
import kotlinx.android.synthetic.main.activity_user_poster.tvTitle
import rx.Observable
import java.util.concurrent.TimeUnit


class NovelPosterActivity : DiaobaoBaseActivity(){
    private var waitDialog:WaitDialog? = null
    private var novelId = 0
    private var objectType = 5
    private var shareUrl = ""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_novel_poster)
        waitDialog = WaitDialog(this,R.style.updateDialog)
        waitDialog?.show()
        initView()
        val bean = intent.getSerializableExtra(Constant.DATA) as NovelDetailBean
        setData(bean)

    }


    fun initView() {

        layBack.setOnClickListener {
            finish()
        }
        layWeixin.setOnClickListener {
            share(ShareType.Weixin)
        }
        layQQ.setOnClickListener {
            share(ShareType.QQ)
        }
        layWeibo.setOnClickListener {
            share(ShareType.Weibo)
        }
        layDownload.setOnClickListener {
            download()
        }

    }


    fun setData(novel: NovelDetailBean) {
        novelId = novel.id
        shareUrl = novel.shareUrl
        objectType = novel.object_type
        ivQRCode.setImageBitmap(ZXingUtils.createQRImage(novel.shareUrl,ScreenUtil.dip2px(this,64f),ScreenUtil.dip2px(this,64f)))

        GlideUtil.displayRoundImage(ivCover, novel.with_image_w, 5)
        tvTitle.text = "《${novel.title}》"
        tvTip.text = novel.tipTxt
        tvAuthor.text = "${novel.user.name} 著"
        tvDesc.text = StringUtil.filterLineFeed(novel.des)
        if (novel.tags.size > 0) {
            tvTag1.text = novel.tags[0].name
            tvTag1.visibility = View.VISIBLE
        }else{
            tvTag1.visibility = View.GONE
        }
        if (novel.tags.size > 1) {
            tvTag2.text = novel.tags[1].name
            tvTag2.visibility = View.VISIBLE
        }else{
            tvTag2.visibility = View.GONE
        }
        Observable.timer(1500,TimeUnit.MILLISECONDS)
                .compose(RxJavaHelper.observeOnMainThread())
                .subscribe {
                    createPic()
                    waitDialog?.dismiss()
                }
    }

    private fun createPic() {
        val bitmap = getViewBitmap(layContent)
        val screenHeight = ScreenUtil.getScreenHeight(this)
        val screenWidth = ScreenUtil.getScreenWidth(this)
        val viewWidth = screenWidth-ScreenUtil.dip2px(this,54f)
        val viewHeight = (screenHeight-ScreenUtil.dip2px(this,94f+88f))
        if (bitmap != null) {
            val picScale = bitmap.height.toFloat()/bitmap.width.toFloat()
            val viewScale = viewHeight.toFloat()/viewWidth.toFloat()
            if (picScale > viewScale) {
                val width = (bitmap.width*(viewHeight.toFloat()/bitmap.height.toFloat())).toInt()
                val params = RelativeLayout.LayoutParams(width,viewHeight)
                params.addRule(RelativeLayout.CENTER_HORIZONTAL)
                //高度固定，宽度自适应
                ivBigPic.layoutParams = params
            }
            ivBigPic.setImageBitmap(bitmap)
        }
    }



    fun share(type:Int) {
        val bitmap = getViewBitmap(layContent)
        val info = ShareBeansInfo()
        info.setSocial_type(type)
        info.setShareUrl(shareUrl)
        info.object_type = "$objectType"
        info.id = "$novelId"
        if (type == ShareType.QQ|| type == ShareType.QQSpace){
            info.setDataType(Constant.ShareDataType.SHARE_DATA_TYPE_IMAGE)
            val tempPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/poster.png"
            BitmapUtil.saveSDcard(bitmap, tempPath)
            info.setImagUrl(tempPath)
        }else if(type == ShareType.Weibo){
            info.setFlag(ShareBeansInfo.NOVEL_SHARE_FLAG)
            val tempPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/temp_poster_${System.currentTimeMillis()}.png"
            BitmapUtil.saveSDcard(bitmap, tempPath)
            info.setImagUrl(tempPath)
        }
        ShareUtils.shareBigPic(this,type,bitmap,info)
    }

    fun download() {
        val bitmap = getViewBitmap(layContent)
        if (bitmap == null) {
            Toast.makeText(this, "图片已保存失败", Toast.LENGTH_SHORT).show()
        }
        val res = FileUtil2.saveImageToGallery(this,bitmap,"${System.currentTimeMillis()}.jpg")
        if (res) {
            Toast.makeText(this, "图片已保存至相册", Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(this, "图片已保存失败", Toast.LENGTH_SHORT).show()
        }
    }


    var bitmap:Bitmap? = null

    private fun getViewBitmap(view: View): Bitmap? {
        if (bitmap != null) {
            return bitmap
        }

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.RGB_565)
        bitmap?.density = resources.displayMetrics.densityDpi
        val canvas = Canvas(bitmap!!)
        view.draw(canvas)
        return bitmap
    }

    companion object{

        fun startActivity(context: Context,bean: NovelDetailBean) {
            val intent = Intent(context,NovelPosterActivity::class.java)
            intent.putExtra(Constant.DATA,bean)
            context.startActivity(intent)
        }
    }
}